package com.realjinge.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.realjinge.api.MpApi;
import com.realjinge.api.WebApi;
import com.realjinge.api.util.JsSignUtil;
import com.realjinge.config.WeChatConfig;
import com.realjinge.entity.WeChatUser;
import com.realjinge.service.WeChatUserService;
import com.realjinge.utils.ErrorCodeUtils;

/**
 * 
 * @author realjinge
 *
 */
@Controller
public class ViewController {
	@Resource
	private WeChatUserService weChatUserService;

	@RequestMapping(value = "index.do", method = { RequestMethod.GET, RequestMethod.POST })
	public String toIndex(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String loginOut = request.getParameter("loginOut");
		if (loginOut != null && "01".equals(loginOut)) {
			request.getSession().removeAttribute("token");
			return "view/index";
		}

		String token = request.getParameter("token");
		if (null == token || "".equals(token)) {
			token = (String) request.getSession().getAttribute("token");
		}
		map.put("token", token);

		String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		Map<String, String> ret = new HashMap<String, String>();
		ret = JsSignUtil.sign(url);

		map.addAttribute("ret", ret);

		return "view/index";
	}

	/**
	 * 
	 * 微信测试公众号页面请求
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "view.do", method = { RequestMethod.GET, RequestMethod.POST })
	public String doView(HttpServletRequest request, HttpServletResponse response, ModelMap map) {

		String code = request.getParameter("code");
		String state = request.getParameter("state");
		// 根据code获取openID
		if (code == null || code.equals("") || state == null || !StringUtils.isNumeric(state)) {
			map.addAttribute("errmsg", ErrorCodeUtils.errCode("404", "获取参数失败！"));
			return "view/error";
		} else if ("share".equals(code)) {
			// 分享
			return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeChatConfig.APPID
					+ "&redirect_uri=http%3a%2f%2f" + WeChatConfig.DOMAIN_NAME
					+ "%2fweChat%2fview.do&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";
		} else {
			String openID = WebApi.getAccessTokenByCode(code);

			WeChatUser user = weChatUserService.getWeChatUser(openID);

			if (user == null) {
				// 根据openID获取用户信息
				user = MpApi.getUserInfo(openID);
				if (user != null) {
					weChatUserService.setWeChatUser(user);
				} else {
					System.out.println("获取用户信息失败！");
					return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeChatConfig.APPID
							+ "&redirect_uri=http%3a%2f%2f" + WeChatConfig.DOMAIN_NAME
							+ "%2fweChat%2fview.do&response_type=code&scope=snsapi_base&state=" + state
							+ "#wechat_redirect";
				}
			} else {
				// System.out.println(user);
			}

			JSONObject json = new JSONObject();
			switch (Integer.parseInt(state)) {
			// 登录
			case 1:
				request.getSession().setAttribute("token", openID);
				// return toIndex(request, response, map);
				return "redirect:index.do";
			case 2:
				json.put("code", code);
				json.put("state", state);
				json.put("openid", openID);
				break;
			default:
				break;
			}

			map.addAttribute("msg", json);
			if (user != null) {
				map.addAttribute("user", user);
			}
		}
		return "view/test";
	}

	/**
	 * 输出JSON字符串
	 * 
	 * @param response
	 * @param jsonMsg
	 */
	protected void out(HttpServletResponse response, String jsonMsg) {

		try {
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().write(jsonMsg);
		} catch (IOException e) {
			// do nothing
		}

	}

}
